import network
import time
import uftpd
from ftpadvanced import AdvancedFTP


def print_important_msg(str1, max_len=40, a_char='#'):
    if len(str1) > max_len:
        max_len += 2
    num1 = int((max_len - len(str1)) / 2)
    num2 = num1 + (max_len - len(str1)) % 2
    print(a_char * num1 + str1 + a_char * num2)
    print('{}'.format(str1))
    print(a_char * max_len)
    print('')


def connect_wifi(uuid, pwd):
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    for _ in range(10):
        sta_if.connect(uuid, pwd)
        time.sleep(1)
        if sta_if.isconnected():
            print_important_msg('Connect Wifi {}'.format(uuid))
            break
        time.sleep(9)
        print('try to connect {} wifi {} times'.format(uuid, _))
    else:
        print('Fail to connect {} wifi'.format(uuid))


def start_ftp_server(port=21):
    uftpd.start(port=21, splash=False)
    sta_if = network.WLAN(network.STA_IF)
    print_important_msg('ESP32 FTP Server: ftp://{}:{}'.format(sta_if.ifconfig()[0], port))


def connect_ftp_server(ip='192.168.2.232', port=21):
    ftp = AdvancedFTP(ip, port)
    ftp.login('admin', '123456')
    files = ftp.nlst()
    print(files)
    return ftp


def download_file(_file_path, _ftp):
    global __Ftp_Have_Download
    __Ftp_Have_Download = 0
    _ftp.voidcmd('TYPE I')
    _sizes = _ftp.size(_file_path)
    print('ftp server {} sizes={}'.format(_file_path, _sizes))

    def handle_download(_block, f):
        global __Ftp_Have_Download
        __Ftp_Have_Download += len(_block)
        f.write(_block)
        progress = '{:.1f}% {}|{}'.format(100.0 * __Ftp_Have_Download / _sizes, __Ftp_Have_Download, _sizes)
        print('ftp download {} progress={}'.format(_file_path, progress))

    with open(_file_path, "wb") as _f_write:
        _result = _ftp.retrbinary('RETR {}'.format(_file_path),
                                  lambda block: handle_download(block, _f_write))

    print('ftp download {} return code={}'.format(_file_path, _result))


def upload_file(_file_path, _ftp):
    with open(_file_path, 'rb') as fp:
        result = _ftp.storbinary('STOR {}'.format(_file_path), fp)
        print('ftp upload {} return code={}'.format(_file_path, result))


connect_wifi("805-2.4G", "28052805")
start_ftp_server()
# connected_ftp_server = connect_ftp_server()
# download_file('aaaaaa.dxf', connected_ftp_server)
# upload_file('README.pdf', connected_ftp_server)

from tft.test_tft import test_lcd

test_lcd()
